{% extends 'base.html' %}
{% load static %}

{% block title %}模板列表 - CFS Web System{% endblock %}

{% block page_type %}template-list{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item active">模板列表</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 页面标题 -->
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-list me-2"></i>模板列表</h2>
            <div class="btn-group">
                <button type="button" class="btn btn-outline-secondary" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i> 刷新
                </button>
                <a href="{% url 'template_management:template_create' %}" class="btn btn-primary">
                    <i class="fas fa-plus"></i> 创建模板
                </a>
            </div>
        </div>
    </div>
</div>

<!-- 搜索和过滤 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <label for="search" class="form-label">搜索模板</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="search" name="search" 
                                   placeholder="输入模板名称或描述" value="{{ request.GET.search }}">
                            <button class="btn btn-outline-secondary" type="submit">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <label for="status" class="form-label">状态</label>
                        <select class="form-select" id="status" name="status">
                            <option value="">全部状态</option>
                            <option value="active" {% if request.GET.status == 'active' %}selected{% endif %}>启用</option>
                            <option value="inactive" {% if request.GET.status == 'inactive' %}selected{% endif %}>禁用</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="sort" class="form-label">排序</label>
                        <select class="form-select" id="sort" name="sort">
                            <option value="-created_at" {% if request.GET.sort == '-created_at' %}selected{% endif %}>创建时间(新到旧)</option>
                            <option value="created_at" {% if request.GET.sort == 'created_at' %}selected{% endif %}>创建时间(旧到新)</option>
                            <option value="name" {% if request.GET.sort == 'name' %}selected{% endif %}>名称(A-Z)</option>
                            <option value="-name" {% if request.GET.sort == '-name' %}selected{% endif %}>名称(Z-A)</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-filter"></i> 筛选
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 模板列表 -->
<div class="row">
    <div class="col-12">
        {% if templates %}
            <div class="row">
                {% for template in templates %}
                <div class="col-lg-6 col-xl-4 mb-4">
                    <div class="card template-card h-100">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">
                                <i class="fas fa-file-alt me-2"></i>
                                {{ template.name|truncatechars:20 }}
                            </h6>
                            <div class="dropdown">
                                <button class="btn btn-sm btn-outline-secondary" type="button" 
                                        data-bs-toggle="dropdown">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                                <ul class="dropdown-menu dropdown-menu-end">
                                    <li>
                                        <a class="dropdown-item" href="{% url 'template_management:template_detail' template.id %}">
                                            <i class="fas fa-eye me-2"></i>查看详情
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="{% url 'template_management:template_edit' template.id %}">
                                            <i class="fas fa-edit me-2"></i>编辑
                                        </a>
                                    </li>

                                    <li><hr class="dropdown-divider"></li>
                                    <li>
                                        <a class="dropdown-item text-danger" href="#" 
                                        onclick="deleteTemplate('{{ template.id }}', '{{ template.name|escapejs }}')">
                                            <i class="fas fa-trash me-2"></i>删除
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="card-body">
                            <p class="text-muted mb-3">{{ template.description|default:'暂无描述'|truncatechars:80 }}</p>
                            
                            <div class="row mb-3">
                                <div class="col-6">
                                    <small class="text-muted">状态:</small><br>
                                    {% if template.is_active %}
                                        <span class="badge bg-success">启用</span>
                                    {% else %}
                                        <span class="badge bg-secondary">禁用</span>
                                    {% endif %}
                                </div>
                                <div class="col-6">
                                    <small class="text-muted">使用次数:</small><br>
                                    <span class="fw-bold">{{ template.usage_count|default:0 }}</span>
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-12">
                                    <small class="text-muted">配置字段:</small><br>
                                    {% if template.config %}
                                        <span class="badge bg-info me-1">{{ template.config.source_columns|length }} 源列</span>
                                        <span class="badge bg-warning me-1">{{ template.config.target_columns|length }} 目标列</span>
                                    {% else %}
                                        <span class="text-muted">未配置</span>
                                    {% endif %}
                                </div>
                            </div>
                            
                            <div class="row text-muted">
                                <div class="col-12">
                                    <small>
                                        <i class="fas fa-calendar me-1"></i>
                                        创建: {{ template.created_at|date:'Y-m-d H:i' }}
                                    </small>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer bg-transparent">
                            <div class="btn-group w-100">
                                <a href="{% url 'template_management:template_detail' template.id %}" 
                                   class="btn btn-outline-primary btn-sm">
                                    <i class="fas fa-eye"></i> 查看
                                </a>
                                <a href="{% url 'template_management:template_edit' template.id %}" 
                                   class="btn btn-outline-success btn-sm">
                                    <i class="fas fa-edit"></i> 编辑
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
            
            <!-- 分页 -->
            {% if is_paginated %}
            <nav aria-label="模板列表分页">
                <ul class="pagination justify-content-center">
                    {% if page_obj.has_previous %}
                        <li class="page-item">
                            <a class="page-link" href="?{% if request.GET.search %}search={{ request.GET.search }}&{% endif %}{% if request.GET.status %}status={{ request.GET.status }}&{% endif %}{% if request.GET.sort %}sort={{ request.GET.sort }}&{% endif %}page=1">
                                <i class="fas fa-angle-double-left"></i>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?{% if request.GET.search %}search={{ request.GET.search }}&{% endif %}{% if request.GET.status %}status={{ request.GET.status }}&{% endif %}{% if request.GET.sort %}sort={{ request.GET.sort }}&{% endif %}page={{ page_obj.previous_page_number }}">
                                <i class="fas fa-angle-left"></i>
                            </a>
                        </li>
                    {% endif %}
                    
                    {% for num in page_obj.paginator.page_range %}
                        {% if page_obj.number == num %}
                            <li class="page-item active">
                                <span class="page-link">{{ num }}</span>
                            </li>
                        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                            <li class="page-item">
                                <a class="page-link" href="?{% if request.GET.search %}search={{ request.GET.search }}&{% endif %}{% if request.GET.status %}status={{ request.GET.status }}&{% endif %}{% if request.GET.sort %}sort={{ request.GET.sort }}&{% endif %}page={{ num }}">{{ num }}</a>
                            </li>
                        {% endif %}
                    {% endfor %}
                    
                    {% if page_obj.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="?{% if request.GET.search %}search={{ request.GET.search }}&{% endif %}{% if request.GET.status %}status={{ request.GET.status }}&{% endif %}{% if request.GET.sort %}sort={{ request.GET.sort }}&{% endif %}page={{ page_obj.next_page_number }}">
                                <i class="fas fa-angle-right"></i>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?{% if request.GET.search %}search={{ request.GET.search }}&{% endif %}{% if request.GET.status %}status={{ request.GET.status }}&{% endif %}{% if request.GET.sort %}sort={{ request.GET.sort }}&{% endif %}page={{ page_obj.paginator.num_pages }}">
                                <i class="fas fa-angle-double-right"></i>
                            </a>
                        </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        {% else %}
            <!-- 空状态 -->
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="fas fa-file-alt fa-4x text-muted mb-4"></i>
                    <h4 class="text-muted mb-3">暂无模板</h4>
                    {% if request.GET.search or request.GET.status %}
                        <p class="text-muted mb-4">没有找到符合条件的模板，请尝试调整搜索条件。</p>
                        <a href="{% url 'template_management:template_list' %}" class="btn btn-outline-primary me-2">
                            <i class="fas fa-times"></i> 清除筛选
                        </a>
                    {% else %}
                        <p class="text-muted mb-4">还没有创建任何模板，立即创建第一个模板开始使用系统。</p>
                    {% endif %}
                    <a href="{% url 'template_management:template_create' %}" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 创建模板
                    </a>
                </div>
            </div>
        {% endif %}
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle text-danger me-2"></i>确认删除
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除模板 <strong id="delete-template-name"></strong> 吗？</p>
                <p class="text-danger"><small>此操作不可撤销，相关的处理任务可能会受到影响。</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirm-delete-btn">
                    <i class="fas fa-trash"></i> 确认删除
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 删除模板
function deleteTemplate(templateId, templateName) {
    document.getElementById('delete-template-name').textContent = templateName;
    
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    deleteModal.show();
    
    document.getElementById('confirm-delete-btn').onclick = function() {
        // 发送删除请求
        fetch(`/template-management/api/templates/${templateId}/`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': CFS.utils.getCsrfToken(),
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            deleteModal.hide();
            
            if (data.success) {
                showSuccess(data.message || '模板删除成功');
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } else {
                showError('删除失败: ' + (data.error || data.message || '未知错误'));
            }
        })
        .catch(error => {
            deleteModal.hide();
            showError('删除失败: ' + error.message);
        });
    };
}



// 使用模板
function useTemplate(templateId) {
    window.location.href = `/data-generation/?template_id=${templateId}`;
}

// 自动提交表单当选择框改变时
document.addEventListener('DOMContentLoaded', function() {
    const statusSelect = document.getElementById('status');
    const sortSelect = document.getElementById('sort');
    
    if (statusSelect) {
        statusSelect.addEventListener('change', function() {
            this.form.submit();
        });
    }
    
    if (sortSelect) {
        sortSelect.addEventListener('change', function() {
            this.form.submit();
        });
    }
});

// 显示确认对话框
function showConfirm(message, title = '确认操作', confirmText = '确定', cancelText = '取消') {
    return new Promise((resolve) => {
        const modalId = 'confirm-modal-' + Date.now();
        const modalHtml = `
            <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${title}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p>${message}</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">${cancelText}</button>
                            <button type="button" class="btn btn-primary confirm-btn">${confirmText}</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        const modal = new bootstrap.Modal(document.getElementById(modalId));
        
        document.querySelector(`#${modalId} .confirm-btn`).addEventListener('click', () => {
            document.getElementById(modalId).dataset.resolved = 'true';
            modal.hide();
            resolve(true);
        });
        
        document.getElementById(modalId).addEventListener('hidden.bs.modal', function() {
            if (!this.dataset.resolved) {
                resolve(false);
            }
            this.remove();
        });
        
        modal.show();
    });
}
</script>
{% endblock %}